//
//  XuanTiViewController.m
//  ZhiBoYuan
//
//  Created by apple on 2018/4/20.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "XuanTiViewController.h"

#import "XuanTiCell.h"

static NSString *ident = @"XuanTiCell";

#import "QuXuanTiVC.h"

#import "XinJIanSJViewController.h"

#import "ShiJuanShiTiVC.h"

#import "TongJIFenXiVC.h"

@interface XuanTiViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) NSInteger pageIndex;
@end

@implementation XuanTiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"选题";
    
    NSLog(@"%@",self.teskID);
    
    
    [self.view addSubview:self.collectionView];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"新建试卷" style:(UIBarButtonItemStyleDone) target:self action:@selector(open)];
    
}

-(void)setTask:(Task *)task
{
    _task = task;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getdate];
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    _task.paper_count = [NSString stringWithFormat:@"%zd",self.dataArray.count];
    if (self.fresh) {
        self.fresh(_task);
    }
}

#pragma mark -----------------------获取数据------------------------
-(void)getdate
{
    _dataArray = [NSMutableArray array];
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    parameter.body = @{@"task_id":self.teskID};
    
    
    NSString *lastUrl  = @"g=Client&m=Paper&a=taskPaperList";
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NSLog(@"%@",dic);
        
        for (NSDictionary *dicc in dic[@"data"][@"paper_list"]) {
            [_dataArray addObject:dicc];
        }
//        self.dataArray = dic[@"data"][@"paper_list"];
        
        
        NNSLog(@"%@",self.dataArray);
        
        [self.collectionView reloadData];
        
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
}

#pragma mark -----------------------新建试卷------------------------
- (void)open
{
    NSLog(@"新建试卷");
    XinJIanSJViewController *vc = [[XinJIanSJViewController alloc]init];
    
    vc.teskID = self.teskID;
//     __weak __typeof(&*self)weakSelf = self;
    vc.backback = ^(id arr) {
        NSLog(@"添加 刷新页面");
        
//        [weakSelf getdate];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
  

}

-(UICollectionView *)collectionView
{
    if (!_collectionView)
    {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        
        
        _collectionView= [[UICollectionView alloc]initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, ScreenWidth, Screenheight-NAVIGATION_BAR_HEIGHT) collectionViewLayout:layout];
        
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerNib:[UINib nibWithNibName:ident bundle:nil] forCellWithReuseIdentifier:ident];
        
        
    }
    return _collectionView;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    XuanTiCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ident forIndexPath:indexPath];
    
    Paper * p = [[Paper alloc]initWithDictionary:_dataArray[indexPath.row]];
    
    cell.nameLabel.text = [NSString stringWithFormat:@"%@",p.name];
    cell.numberLable.text = [NSString stringWithFormat:@"共%zd题",[p.total_question integerValue]];
    
    
    BTN_MSG_FUNC(cell.delButton, delSender:);
    
    BTN_MSG_FUNC(cell.quXuanTIButton, quXuanTISender:);
    
    BTN_MSG_FUNC(cell.tongJiButton, tongJiSender:);

    return cell;
}


#pragma mark ----------------------- 统计分析 ------------------------
-(void)tongJiSender:(UIButton *)sender{
    
    
    if (self.dataArray.count==0) {
        return;
    }
    TongJIFenXiVC *tognjiFXVC = [[TongJIFenXiVC alloc]init];
    tognjiFXVC.task_id = self.teskID;
    
    
    NSIndexPath *path = [self.collectionView indexPathForCell:(XuanTiCell *)[[sender superview] superview]];
    Paper * p = [[Paper alloc]initWithDictionary:self.dataArray[path.row]];
    
    tognjiFXVC.course_id = p.id;
    tognjiFXVC.isComeFormTi = YES;
    [self.navigationController pushViewController:tognjiFXVC animated:YES];
}

#pragma mark -----------------------删除------------------------
- (void)delSender:(UIButton *)sender
{
    
    if (self.dataArray.count==0) {
        return;
    }
    
    NSIndexPath *path = [self.collectionView indexPathForCell:(XuanTiCell *)[[sender superview] superview]];

    Paper * p = [[Paper alloc]initWithDictionary:self.dataArray[path.row]];
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    
    parameter.body          = @{@"task_id":self.teskID
                                ,@"paper_id":p.id };
    
    NSString *lastUrl       = @"g=Client&m=Paper&a=delTaskPaper";
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NNSLog(@"%@",dic);
        
        NSMutableArray *arr = dic[@"data"];
        
          NNSLog(@"question_list = %@",arr);
        
        if ([dic[@"status"] integerValue] == 200) {

            [self.dataArray removeObjectAtIndex:path.row];
            [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:path.row inSection:0]]];

        }else{
            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:3];
        }

    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];

    
}

#pragma mark ----------------------- 去选题 ------------------------
- (void)quXuanTISender:(UIButton *)sender
{
    if (self.dataArray.count==0) {
        return;
    }

    NSIndexPath *path = [self.collectionView indexPathForCell:(XuanTiCell *)[[sender superview] superview]];
    QuXuanTiVC *vc = [[QuXuanTiVC alloc]init];
    if (self.dataArray.count <= path.row) {
        
        [MBProgressHUD showTextOnly:self.view message:@"数据错误" delay:2];
        return;
    }
    
    Paper * p = [[Paper alloc]initWithDictionary:self.dataArray[path.row]];
    vc.paper_id = p.id;
    
    
    vc.teskID = self.teskID;
    
    vc.blockAdd = ^(id arr) {
        [self.dataArray addObject:@"1"];
        [_collectionView reloadData];
    };
    
    [self.navigationController pushViewController:vc animated:YES];

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%zd",indexPath.row);
    
    ShiJuanShiTiVC *vc = [[ShiJuanShiTiVC alloc]init];
    
     Paper * p = [[Paper alloc]initWithDictionary:self.dataArray[indexPath.row]];
    vc.name = p.name;
    vc.paperID = p.id;
    [self.navigationController pushViewController:vc animated:YES];
}

#define JianGe 20
#define GeShu 2
//定义每个UICollectionView 的大小
- ( CGSize )collectionView:( UICollectionView *)collectionView layout:( UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:( NSIndexPath *)indexPath
{
    //    return CGSizeMake((ScreenWidth - JianGe*(GeShu+1)) / GeShu, (ScreenWidth - JianGe*(GeShu+1)) / GeShu );
//    return CGSizeMake((ScreenWidth - JianGe*(GeShu+1)) / GeShu, (ScreenWidth - JianGe*(GeShu+1)) / GeShu);
    
//    if (iPhone5 ||iPhone6)
//    {
        return CGSizeMake((ScreenWidth - JianGe * (GeShu + 1)) / GeShu,155);
//    }
//    else
//    {
//      return CGSizeMake((ScreenWidth - JianGe *  (GeShu + 1)) / GeShu, (ScreenWidth - JianGe * (GeShu + 1)) / GeShu);
//    }

}


//定义每个UICollectionView 的边距

- ( UIEdgeInsets )collectionView:( UICollectionView *)collectionView layout:( UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:( NSInteger )section
{
    return UIEdgeInsetsMake ( JianGe , JianGe , JianGe , JianGe );
}

//设置水平间距 (同一行的cell的左右间距）

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return JianGe;
}

//垂直间距 (同一列cell上下间距)

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return JianGe;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
